package com.bridgeintelligent.tag.customer.track;

import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import static javax.servlet.http.HttpServletResponse.SC_OK;

@Api(tags = "客群追踪导出服务接口")
@AllArgsConstructor
@RestController
@Slf4j
@RequestMapping(value = "/api/trackExport")
public class TrackExportController {


    private ITrackService trackService;

    @ApiOperation(value = "导出某个标签追踪数据", notes = "追踪数据导出")
    @PostMapping("/exportDim")
    public void exportDim(String condition, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try{

            List<TrackQueryModel> trackQueryModels = JSONUtil.toList(condition, TrackQueryModel.class);
            // 创建工作薄对象
            XSSFWorkbook wb=new XSSFWorkbook();
            CellStyle commonStyle = setStyle(wb);

            if (!CollectionUtils.isEmpty(trackQueryModels)){
                for (TrackQueryModel model:trackQueryModels) {
                    List<List<String>> data = trackService.getRowData(model);
                    createSheet(wb, commonStyle ,data,model.getDimName());
                }
            }
            // 创建文档信息
            try(OutputStream os=response.getOutputStream()) {
                response.reset();
                response.setStatus(SC_OK);
                String fileName = "标签追踪-"+ DateFormatUtils.format(new Date(),"yyyy-MM-dd");
                fileName = new String(fileName.getBytes(),"UTF-8");
                response.setHeader("Content-disposition", String.format("attachment; filename=\"%s.xlsx\"", fileName));
                response.setContentType("application/msexcel");
                wb.write(os);
                os.flush();
            } catch (IOException e) {
                log.error("标签追踪导出异常", e);
                throw new RuntimeException("标签追踪导出异常");
            }
        }catch (Exception e){
            log.error("标签追踪导出异常!", e);
            throw new RuntimeException("标签追踪导出异常!");
        }

    }

    public void createSheet(XSSFWorkbook wb, CellStyle commonStyle ,List<List<String>> data,String dimName) {
        try {
            // 创建sheet
            Sheet sheet = wb.createSheet(dimName);
            if (CollectionUtils.isEmpty(data)) {
                return;
            }
            // 行号
            int rowNum = 0;
            //设置列宽
            for (int i = 0; i < data.get(0).size()+2; i++) {
                sheet.setColumnWidth(i, 3000);
            }
            for (List<String> rowData:data ) {
                Row row = sheet.createRow(rowNum++);
                if (rowNum == 1){
                    row.setHeight((short) 700);
                }
                for (int i = 0; i < rowData.size(); i++) {
                    //列表数据
                    Cell tempCell2 = row.createCell(i);
                    tempCell2.setCellValue(Optional.ofNullable(rowData.get(i)).orElse(""));
                    tempCell2.setCellStyle(commonStyle);
                }
            }
        } catch (Exception e) {
            log.error("导出" + dimName + "追踪数据时出现异常", e);
        }
    }

    public CellStyle setStyle(XSSFWorkbook wb) {
        //表头字体
        Font headerFont = wb.createFont();
        headerFont.setFontName("宋体");
        headerFont.setFontHeightInPoints((short) 18);
        headerFont.setBold(true);
        headerFont.setColor(Font.COLOR_NORMAL);
        //正文字体
        Font contextFont = wb.createFont();
        contextFont.setFontName("宋体");
        contextFont.setFontHeightInPoints((short) 12);
        headerFont.setBold(true);
        //表头样式，左右上下居中
        CellStyle headerStyle = wb.createCellStyle();
        headerStyle.setFont(headerFont);
        // 左右居中
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
        // 上下居中
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headerStyle.setLocked(true);
        // 自动换行
        headerStyle.setWrapText(false);
        //单元格样式，左右上下居中 边框
        CellStyle commonStyle = wb.createCellStyle();
        commonStyle.setFont(contextFont);
        // 左右居中
        commonStyle.setAlignment(HorizontalAlignment.CENTER);
        // 上下居中
        commonStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        commonStyle.setLocked(true);
        // 自动换行
        commonStyle.setWrapText(false);
        //单元格样式，左右上下居中 边框
        CellStyle commonWrapStyle = wb.createCellStyle();
        commonWrapStyle.setFont(contextFont);
        //单元格样式，竖向 边框
        CellStyle verticalStyle = wb.createCellStyle();
        verticalStyle.setFont(contextFont);
        CellStyle commonStyleNoBorder = wb.createCellStyle();
        commonStyleNoBorder.setFont(contextFont);
        commonStyleNoBorder.setLocked(true);
        // 自动换行
        commonStyleNoBorder.setWrapText(false);
        CellStyle alignLeftStyle = wb.createCellStyle();
        alignLeftStyle.setFont(contextFont);
        alignLeftStyle.setLocked(true);
        // 自动换行
        alignLeftStyle.setWrapText(false);
        //单元格样式，左对齐 无边框
        CellStyle alignLeftNoBorderStyle = wb.createCellStyle();
        alignLeftNoBorderStyle.setFont(contextFont);
        alignLeftNoBorderStyle.setLocked(true);
        // 自动换行
        alignLeftNoBorderStyle.setWrapText(false);
        //单元格样式，右对齐
        CellStyle alignRightStyle = wb.createCellStyle();
        alignRightStyle.setFont(contextFont);
        alignRightStyle.setLocked(true);
        // 自动换行
        alignRightStyle.setWrapText(false);
        return commonStyle;
    }

}
